package com.aeye.cloud.ui;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.zip.DataFormatException;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.aeye.android.data.NativeManager;
import com.aeye.android.uitls.BitmapUtils;
import com.aeye.cloud.R;
import com.aeye.cloud.data.SettingData;
import com.aeye.cloud.http.HttpConnectionUtils;
import com.aeye.cloud.http.HttpHandler;
import com.aeye.cloud.utils.ImageLoadUtil;
import com.aeye.cloud.utils.SHA1Util;
import com.aeye.face.AEFaceInterface;
import com.aeye.face.AEFacePack;
import com.aeye.face.AEFaceParam;
import com.aeye.sdk.AEFaceTools;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nostra13.universalimageloader.core.ImageLoader;

public class MainActivity extends Activity implements OnClickListener, AEFaceInterface {
	static final int REQUEST_CAPTURE = 0;
	static final int REQUEST_SELECT = 1;
	static final int REQUEST_POPUP = 2;
	static final int REQUEST_INTRODUCE = 3;

	private Button btSetting, btAutoRecog;
	private ImageView ivPhoto, ivDebug;
	private TextView funcA, funcB, funcC, funcD, funcE, funcF;
	private ProgressDialog mProgress;
	
	private Intent recogIntent = null;
	private TelephonyManager mTelMgr;
	private String deviceId;
	private DemoApplication mApp;
	
	private boolean needModel = false;
	private Uri mCapImage;
	private String modelStr;
	private int mCapMode = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		btSetting = (Button) findViewById(R.id.btSetting);
		btSetting.setOnClickListener(this);
		btAutoRecog = (Button) findViewById(R.id.btAutoRecog);
		btAutoRecog.setOnClickListener(this);
		ivPhoto = (ImageView) findViewById(R.id.ivPhoto);
		ivPhoto.setOnClickListener(this);
		funcA = (TextView) findViewById(R.id.funcA);
		funcA.setOnClickListener(this);
		funcB = (TextView) findViewById(R.id.funcB);
		funcB.setOnClickListener(this);
		funcC = (TextView) findViewById(R.id.funcC);
		funcC.setOnClickListener(this);
		funcD = (TextView) findViewById(R.id.funcD);
		funcD.setOnClickListener(this);
		funcE = (TextView) findViewById(R.id.funcE);
		funcE.setOnClickListener(this);
		funcF = (TextView) findViewById(R.id.funcF);
		funcF.setOnClickListener(this);
		
		ivDebug = (ImageView) findViewById(R.id.ivDebug);

		/*try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			Date stop = format.parse("2017-06-01");
			Date dateCur = new Date();
			if (dateCur.after(stop)) {
				Toast.makeText(this, "已过期", Toast.LENGTH_LONG).show();
				finish();
				return;
			}
		} catch (ParseException e1) {
			e1.printStackTrace();
		}*/
		
		mApp = (DemoApplication) getApplication();
		
		mTelMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		deviceId = mTelMgr.getDeviceId();
		mApp.setDeviceId(deviceId);
		
		AEFacePack.getInstance().AEYE_Init(this);
		mApp.setNeedUpdate(true);
	}
	
	@Override
	protected void onResume() {
		if (mApp.isNeedUpdate()) {
			mApp.setNeedUpdate(false);
			try {
				mProgress = ProgressDialog.show(this, null,
						getString(R.string.loading_model));
				mProgress.setOnKeyListener(new OnKeyListener() {
					
					@Override
					public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
						if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
							mProgress.dismiss();
						}
						return false;
					}
				});
				if (SettingData.getInstance().isServerRecog()) {
					startQueryPerson(deviceId);
				} else {
					needModel = true;
					modelStr = null;
					if (NativeManager.getInstance(this).isExist(deviceId)) {
						needModel = false;
						List<String> list = NativeManager.getInstance(this).getModels(deviceId);
						modelStr = list.get(0);
						ivPhoto.setImageBitmap(BitmapUtils.convertStringToBitmap(modelStr));
					} else {
						ivPhoto.setImageResource(R.drawable.add_image);
					}
					mApp.setModel(modelStr);
					mProgress.dismiss();
				}
					
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		AEFacePack.getInstance().AEYE_Destory(this);
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.btSetting: {
			goSettingActivity();
			break;
		}
		case R.id.btAutoRecog: {
			startRecog(false);
			break;
		}
		case R.id.ivPhoto: {
			mCapMode = R.id.ivPhoto;
			if (needModel) {
				takePhoto();
			} else {
				showAlertDialog();
			}
			break;
		}
		case R.id.funcA: {
			mCapMode = R.id.funcA;
//			takePhoto();
			Intent intent = new Intent(this, SelectPicPopupWindow.class);
			startActivityForResult(intent, REQUEST_POPUP);
			break;
		}
		case R.id.funcB: {
			mCapMode = R.id.funcB;
//			takePhoto();
			Intent intent = new Intent(this, SelectPicPopupWindow.class);
			startActivityForResult(intent, REQUEST_POPUP);
			break;
		}
		case R.id.funcC: {
			mCapMode = R.id.funcC;
			if(SettingData.getInstance().isIntroduce()) {
				Intent intent = new Intent(this, IntroduceActivity.class);
				startActivityForResult(intent, REQUEST_INTRODUCE);
			} else {
				startRecog(true);
			}
			break;
		}
		case R.id.funcD: {
			mCapMode = R.id.funcD;
//			takePhoto();
			Intent intent = new Intent(this, SelectPicPopupWindow.class);
			startActivityForResult(intent, REQUEST_POPUP);
			break;
		}
		case R.id.funcE: {
			mCapMode = R.id.funcE;
			Intent intent = new Intent(this, SelectPicPopupWindow.class);
			startActivityForResult(intent, REQUEST_POPUP);
//			takePhoto();
			break;
		}
		case R.id.funcF: {
//			startDebug();
			break;
		}
		default:
			break;
		}
	}
	
	/*private void startDebug() {
		recogIntent = new Intent(this, ResultActivity.class);
		SettingData setting = SettingData.getInstance();
		setting.updateData(this);

		Bundle paras = new Bundle();
		paras.putInt(AEFaceParam.SingleAliveMotionTime, setting.getSideTimeout());
		paras.putInt(AEFaceParam.ModelMutiAngleSwitch, 1);
		paras.putInt(AEFaceParam.ContinueFailDetectNum, 4);
		paras.putInt(AEFaceParam.ContinueSuccessDetectNum, 6);
		paras.putInt(AEFaceParam.AliveSwitch, 0);
		paras.putInt(AEFaceParam.VoiceSwitch, setting.isVoice() ? 1 : 0);
		paras.putInt(AEFaceParam.QualitySwitch, 0);
		paras.putInt(AEFaceParam.ModelOverTime, 60);

		paras.putInt(AEFaceParam.ColorBottomBarBg, 0x00000000);
		paras.putInt(AEFaceParam.ColorTopBarBg, 0xEE222222);
		paras.putInt(AEFaceParam.ShowBackButton, 1);

		AEFacePack.getInstance().AEYE_SetListener(this);
		AEFacePack.getInstance().AEYE_SetParameter(paras);
		AEFacePack.getInstance().AEYE_BeginRecog(this);
	}*/
	
	private void showAlertDialog() {
		AlertDialog.Builder alert = new AlertDialog.Builder(this);
		alert.setMessage(R.string.alert_update_model);
		alert.setPositiveButton(R.string.ok,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (SettingData.getInstance().isServerRecog()) {
							try {
								startDelModel();
							} catch (Exception e) {
								e.printStackTrace();
							}
		            	} else {
		            		takePhoto();
		            	}
					}
				});
		alert.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		alert.create().show();
	}

	private void startRecog(boolean onlyAlive) {
		if (onlyAlive) {
			recogIntent = new Intent(this, ResultAliveActivity.class);//需要修改跳转页面
		} else {
			recogIntent = new Intent(this, ResultActivity.class);
		}
		SettingData setting = SettingData.getInstance();
		setting.updateData(this);

		Bundle paras = new Bundle();
		paras.putInt(AEFaceParam.ModelOverTime, setting.getTimeout());
		paras.putInt(AEFaceParam.AliveMotionNum, setting.getPoseNum());
		paras.putInt(AEFaceParam.AliveFirstMotion, setting.getAliveFirstMotion());
		paras.putInt(AEFaceParam.AliveSwitch, (onlyAlive || setting.isAlive()) ? 1 : 0);
		paras.putInt(AEFaceParam.VoiceSwitch, setting.isVoice() ? 1 : 0);
		paras.putInt(AEFaceParam.FetchImageNum, 1);
		paras.putInt(AEFaceParam.ContinueSuccessDetectNum, 6);
		paras.putInt(AEFaceParam.QualitySwitch, setting.isQuality() ? 1 : 0);
		paras.putInt(AEFaceParam.SingleAliveMotionTime, setting.getSideTimeout());
		paras.putInt(AEFaceParam.ModelMutiAngleSwitch, setting.isSideMotion() ? 1 : 0);
		paras.putInt(AEFaceParam.ContinueFailDetectNum, setting.getLostFace());

		paras.putInt(AEFaceParam.ColorBottomBarBg, 0x00000000);
		paras.putInt(AEFaceParam.ColorTopBarBg, 0xEE222222);
		paras.putInt(AEFaceParam.ShowBackButton, 1);

		AEFacePack.getInstance().AEYE_SetListener(this);
		AEFacePack.getInstance().AEYE_SetParameter(paras);
		AEFacePack.getInstance().AEYE_BeginRecog(this);
	}
	
	@Override
	public void onStart(int value, String data) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPrompt(int value, String data) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProcess(int value, String data) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onFinish(int value, String data) {
		Log.d("ZDX", "onFinish code" + value + " data:" + data);
		recogIntent.putExtra("VALUE", value);
		mApp.setSnapData(data);
		recogIntent.putExtra("DATA", decodeError(value));
		
		startActivity(recogIntent);
	}
	
	private String decodeError(int value) {
		switch(value) {
		default:
		case AEFacePack.SUCCESS:
			if (AEFacePack.getInstance().isAliveOff()) {
				return getString(R.string.capture_success);
			}
			return getString(R.string.alive_success);
		case AEFacePack.ERROR_FAIL:
			return getString(R.string.capture_fail);
		case AEFacePack.ERROR_TIMEOUT:
			return getString(R.string.recog_timeout);
		case AEFacePack.ERROR_CANCEL:
			return getString(R.string.user_cancel);
		case AEFacePack.ERROR_CAMERA:
			return getString(R.string.camera_error);
		}
	}
	
	/*@Override
	public void onSnapFinish(int value, String data) {
//		Log.d("ZDX", "onSnapFinish" + data);
		mApp.setSnapData(data);
	}

	@Override
	public void onRecogFinish(int value, String data) {
		Log.e("ZDX", "onRecogFinish" + data);

		recogIntent.putExtra("VALUE", value);
		recogIntent.putExtra("DATA", data);
		
		startActivity(recogIntent);
	}*/

	private void takePhoto() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File sd = Environment.getExternalStorageDirectory();
		String path = sd.getPath() + "/aeye";
		File file = new File(path);
		if (!file.exists())
			file.mkdir();

		mCapImage = Uri.fromFile(new File(file, "capture.jpg"));

		intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapImage);
		intent.putExtra("camerasensortype", 2);
		intent.putExtra("return-data", true);
		try {
			startActivityForResult(intent, REQUEST_CAPTURE);
		} catch (ActivityNotFoundException e) {
		}
	}

	private void pickPhoto() {
		Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
		openAlbumIntent.setType("image/*");
		openAlbumIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
		openAlbumIntent.addCategory(Intent.CATEGORY_OPENABLE);
		startActivityForResult(openAlbumIntent, REQUEST_SELECT);
	}
	
	/*private String getRealFilePath(final Context context, final Uri uri) {
		if (null == uri)
			return null;
		final String scheme = uri.getScheme();
		String data = null;
		if (scheme == null)
			data = uri.getPath();
		else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
			data = uri.getPath();
		} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
			Cursor cursor = context.getContentResolver().query(uri,
					new String[] { ImageColumns.DATA }, null, null, null);
			if (null != cursor) {
				if (cursor.moveToFirst()) {
					int index = cursor.getColumnIndex(ImageColumns.DATA);
					if (index > -1) {
						data = cursor.getString(index);
					}
				}
				cursor.close();
			}
		}
		return data;
	}*/

	/*private int getBitmapDegree(String path) {
		int degree = 0;
		try {
			// 从指定路径下读取图片，并获取其EXIF信息
			ExifInterface exifInterface = new ExifInterface(path);
			// 获取图片的旋转信息
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			Log.e("jxf", "orientation" + orientation);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}*/
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_CAPTURE: {
			if (resultCode == RESULT_OK) {
				if (mCapImage != null) {
					/*String path = mCapImage.getPath();
//					Bitmap bitmap = BitmapFactory.decodeFile(path);
					
					Matrix matrix = new Matrix();  
		            matrix.postRotate(getBitmapDegree(path));  
		            Bitmap orig = BitmapFactory.decodeFile(path);
		            Bitmap bitmap = Bitmap.createBitmap(orig, 0, 0, orig.getWidth(), orig.getHeight(), matrix, true);*/
					String cameraImage = mCapImage.toString();
					ImageLoader.getInstance().clearMemoryCache();
					ImageLoadUtil.loadImage(cameraImage, ivDebug);
					Bitmap bitmap = ImageLoadUtil.getImage(cameraImage);
					if (cameraImage != null) {
						MediaScannerConnection.scanFile(this,
								new String[] { cameraImage.substring(7) }, null, null);
					}
					if (mCapMode == R.id.funcD) {
	            		goQualityResult(bitmap);
	            	} else if (mCapMode == R.id.funcE) {
	            		goFaceResult(bitmap);
	            	} else {
			            Bitmap face = AEFaceTools.getInstance().AEYE_CutPic(bitmap, 240, 240);
			            try {
				            if (face != null) {
				            	if (mCapMode == R.id.ivPhoto) {
				            		modelStr = BitmapUtils.convertIconToString(face);
				            		mApp.setModel(modelStr);
					            	ivPhoto.setImageBitmap(face);
					            	if (SettingData.getInstance().isServerRecog()) {
					            		startModel(modelStr);
					            	} else {
					            		if (NativeManager.getInstance(this).isExist(deviceId)) {
					            			NativeManager.getInstance(this).deleteModel(deviceId);
					            		}
					            		NativeManager.getInstance(this).addModel(deviceId, modelStr);
					            	}
				            	} else if (mCapMode == R.id.funcA) {
				            		goOneResult(face);
				            	} else if (mCapMode == R.id.funcB) {
				            		goCompareResult(face);
				            	}
				            } else {
				            	Toast.makeText(this, R.string.face_no_detected, Toast.LENGTH_SHORT).show();
				            }
						} catch (Exception e) {
							e.printStackTrace();
						}
	            	}
				}
			}
			break;
		}
		case REQUEST_SELECT: {
			if (resultCode == RESULT_OK && null != data) {
				try {
					ImageLoadUtil.loadImage(data.getData().toString(), ivDebug);
					Bitmap bitmap = ImageLoadUtil.getImage(data.getData().toString());
//					ContentResolver resolver = getContentResolver();
//					Bitmap bitmap = BitmapFactory.decodeStream(resolver.openInputStream(data.getData()));
					if (mCapMode == R.id.funcD) {
	            		goQualityResult(bitmap);
	            	} else if (mCapMode == R.id.funcE) {
	            		goFaceResult(bitmap);
	            	} else if (mCapMode == R.id.funcA || mCapMode == R.id.funcB) {
			            Bitmap face = AEFaceTools.getInstance().AEYE_CutPic(bitmap, 240, 240);
			            try {
				            if (face != null) {
				            	if (mCapMode == R.id.ivPhoto) {
				            		modelStr = BitmapUtils.convertIconToString(face);
				            		mApp.setModel(modelStr);
					            	ivPhoto.setImageBitmap(face);
						            startModel(modelStr);
				            	} else if (mCapMode == R.id.funcA) {
				            		goOneResult(face);
				            	} else if (mCapMode == R.id.funcB) {
				            		goCompareResult(face);
				            	}
				            } else {
				            	Toast.makeText(this, R.string.face_no_detected, Toast.LENGTH_SHORT).show();
				            }
						} catch (Exception e) {
							e.printStackTrace();
						}
	            	}
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
			break;
		}
		case REQUEST_POPUP: {
			switch(resultCode) {
			case SelectPicPopupWindow.RESULT_CANCEL:
				break;
			case SelectPicPopupWindow.RESULT_CAMERA:
				takePhoto();
				break;
			case SelectPicPopupWindow.RESULT_ALBUM:
				pickPhoto();
				break;
			default:
				break;
			}
			break;
		}
		
		case REQUEST_INTRODUCE: {
			if (resultCode == RESULT_OK) {
				startRecog(true);
			}
			break;
		}
		default:
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void goOneResult(Bitmap face) {
		String image = BitmapUtils.convertIconToString(face);
		mApp.setCompare(image);
		Intent intent = new Intent(this, ResultOneActivity.class);
		startActivity(intent);
	}

	private void goCompareResult(Bitmap face) {
		String image = BitmapUtils.convertIconToString(face);
		mApp.setCompare(image);
		Intent intent = new Intent(this, CompareActivity.class);
		startActivity(intent);
	}
	
	
	private void goQualityResult(Bitmap face) {
		String image = BitmapUtils.convertIconToString(face);
		mApp.setCompare(image);
		Intent intent = new Intent(this, ResultQualityActivity.class);
		startActivity(intent);
	}
	
	private void goFaceResult(Bitmap face) {
		String image = BitmapUtils.convertIconToString(face);
		mApp.setCompare(image);
		Intent intent = new Intent(this, ResultFaceActivity.class);
		startActivity(intent);
	}
	
	private void goSettingActivity() {
		Intent intent = new Intent(this, SettingActivity.class);
		startActivity(intent);
	}

	public void startDelModel() throws Exception {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("apiKey", SHA1Util.API_KEY));
		params.add(new BasicNameValuePair("personId", SettingData.getInstance().getPersonId()+""));
//		params.add(new BasicNameValuePair("bioType", "1"));

		params.add(new BasicNameValuePair("apiSign", SHA1Util.encodeSHA(params)));
		new HttpConnectionUtils(handler).post(SettingData.getInstance().getServerAddr()
				+ "/person/empty", params, SettingData.API_DELETE);
	}
	
	public void startQueryPerson(String id) throws Exception {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("apiKey", SHA1Util.API_KEY));
//		params.add(new BasicNameValuePair("cardType", "1"));
		params.add(new BasicNameValuePair("identifyCard", id));
		
		params.add(new BasicNameValuePair("apiSign", SHA1Util.encodeSHA(params)));
		new HttpConnectionUtils(handler).post(SettingData.getInstance().getServerAddr()
				+ "/person/get_by_identifycard", params, SettingData.API_QUERY);
	}

	public void startCreatePerson(String name, String id) throws Exception {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("apiKey", SHA1Util.API_KEY));
//		params.add(new BasicNameValuePair("address", "长沙市"));
//		params.add(new BasicNameValuePair("personNati", "中国"));
		params.add(new BasicNameValuePair("sex", "0"));
//		params.add(new BasicNameValuePair("cardType", "1"));
		params.add(new BasicNameValuePair("groupId", SettingData.GROUP_ID));
		params.add(new BasicNameValuePair("personName", name));
		params.add(new BasicNameValuePair("identifyCard", id));
		
		params.add(new BasicNameValuePair("apiSign", SHA1Util.encodeSHA(params)));
		new HttpConnectionUtils(handler).post(SettingData.getInstance().getServerAddr()
				+ "/person/create", params, SettingData.API_ADD);
	}
	
	public void startModel(String photo) throws Exception {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("apiKey", SHA1Util.API_KEY));
		params.add(new BasicNameValuePair("base64Pics", photo));
		params.add(new BasicNameValuePair("personId", SettingData.getInstance().getPersonId()+""));
		params.add(new BasicNameValuePair("bioType", "1"));
		
		params.add(new BasicNameValuePair("apiSign", SHA1Util.encodeSHA(params)));
		new HttpConnectionUtils(handler).post(SettingData.getInstance().getServerAddr()
				+ "/feature/face/add", params, SettingData.API_MODEL);
	}
	
	public void startGetModel() throws Exception {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("apiKey", SHA1Util.API_KEY));
		params.add(new BasicNameValuePair("personId", SettingData.getInstance().getPersonId()+""));
		params.add(new BasicNameValuePair("bioType", "1"));

		params.add(new BasicNameValuePair("apiSign", SHA1Util.encodeSHA(params)));
		new HttpConnectionUtils(handler).post(SettingData.getInstance().getServerAddr()
				+ "/feature/face/get_list", params, SettingData.API_GETMODEL);
	}
	
	private Handler handler = new HttpHandler(this) {
		
		protected void succeed(String str) {

			try {
				JSONObject mJsonObject = JSONObject.parseObject(str);
				int apiId = mJsonObject.getIntValue("APIID");
				int resultCode = mJsonObject.getIntValue("resultCode");
				String message = mJsonObject.getString("message");
				
				if (resultCode == 0) {
					if(apiId == SettingData.API_QUERY) {
						JSONObject obj = mJsonObject.getJSONObject("data");
						if (obj != null) {
							long personId = obj.getLongValue("personId");
							SettingData.getInstance().setPersonId(personId);
							int face = obj.getIntValue("face");
							if (face == 1) {
								startGetModel();
								needModel = false;
							} else {
								needModel = true;
								mProgress.dismiss();
							}
						} else {
							startCreatePerson("Android Mobile", deviceId);
						}
					} else if(apiId == SettingData.API_GETMODEL) {
						JSONArray array = mJsonObject.getJSONArray("data");
						if (array != null) {
							JSONObject item = array.getJSONObject(0);
							String img = item.getString("picdata");
							if (img != null) {
								ivPhoto.setImageBitmap(
										BitmapUtils.convertStringToBitmap(img));
								modelStr = img;
								mApp.setModel(modelStr);
							}
						}
						mProgress.dismiss();
					} else if (apiId == SettingData.API_ADD) {
						JSONObject obj = mJsonObject.getJSONObject("data");
						long personId = obj.getLongValue("personId");
						SettingData.getInstance().setPersonId(personId);
						needModel = true;
						mProgress.dismiss();
					} else if (apiId == SettingData.API_DELETE) {
						takePhoto();
					} else if (apiId == SettingData.API_COMPN) {
						
					}
				} else {
					if (apiId == SettingData.API_ADD) {
						Toast.makeText(getApplicationContext(),
								R.string.create_person_failed,
								Toast.LENGTH_LONG).show();
					} else if (apiId == SettingData.API_QUERY) {
						Toast.makeText(getApplicationContext(),
								R.string.check_person_failed,
								Toast.LENGTH_LONG).show();
					}
				}
			} catch (Exception e) {
				mProgress.dismiss();
				Toast.makeText(getApplicationContext(),
						R.string.json_parse_e, Toast.LENGTH_LONG)
						.show();
				e.printStackTrace();
			}
		};

		protected void connectError(android.os.Message message) {
			mProgress.dismiss();
			Toast.makeText(getApplicationContext(),
					R.string.net_error, Toast.LENGTH_LONG).show();
		};
	};
}
